package com.yxy.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class RandomVerifyCodeUtil {
    private static final String VERIFY_CODES = "0123456789";

    public static String generateRandomString(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int code = new Random().nextInt(VERIFY_CODES.length());
            char c = VERIFY_CODES.charAt(code);
            sb.append(c);
        }
        return sb.toString();
    }

    // 未使用
    public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String captcha = RandomVerifyCodeUtil.generateRandomString(); // 生成6位随机字符串
        HttpSession session = request.getSession();
        session.setAttribute("captcha", captcha); // 存储到Session

        BufferedImage image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, 100, 50);
        g.setColor(Color.BLACK);
        g.setFont(new Font("Arial", Font.BOLD, 24));
        g.drawString(captcha, 10, 35);

        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
}
